<?php
namespace app\console\controller;

use app\console\model\GiftOrderTwo as FeedbackTypeModel;
use think\Request;
use think\Url;
use think\Db;
use think\Controller;
use think\Response;
use think\Loader;

class GiftOrderTwo extends Controller
{
    /*
     * 列表
     */
    public function index()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['id'] = ['gt', 0];
        if (!empty($inquire['title'])) $condition['order_number|order_id|car_number|username|tel|sjyr|car_tel|car_number2|car_name'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode('/', $inquire['interval_timer']);
            $condition['create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        if(!empty($inquire['order_id'])) $condition['order_id'] = ['eq',$inquire['order_id']];
        // 读取参数

        $data = FeedbackTypeModel::where($condition)->order(['id' => 'desc'])->paginate(20, false, ['query' => $inquire])->each(function ($item,$key){
            //$item->status = Db::name('order')->where('id',$item->order_id)->value('status');
        });

        return $this->fetch('index', [
            'mate_title' => '反馈分类列表',
            'data'       => $data
        ]);
    }

    public function excel()
    {
        // 获取参数
        $inquire = Request::instance()->param();

        // 搜索条件
        $condition['id'] = ['gt', 0];
        if (!empty($inquire['title'])) $condition['order_number|order_id|car_number|username|tel|sjyr|car_tel|car_number2|car_name'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode('/', $inquire['interval_timer']);
            $condition['create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        if(!empty($inquire['order_id'])) $condition['order_id'] = ['eq',$inquire['order_id']];
        // 读取参数
        $data = FeedbackTypeModel::where($condition)->order(['id' => 'desc'])->select()->each(function($item,$key){
            $item->status = $item->status == 1 ? '未确认' : '已确认';
        });

        $this->push($data,'礼包二级订单');
        return $this->fetch('index', [
            'mate_title' => '反馈分类列表',
            'data'       => $data
        ]);
    }


    /*
     * 添加
     */
    public function create()
    {
        $order_id = Request::instance()->param('order_id');
        if (Request::instance()->isPost()) {
            $data = Request::instance()->param();
            // 验证
            $validate = Loader::validate('FeedbackType');
            //if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            //halt($data);
            $dispose = (new FeedbackTypeModel())->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index',Request::instance()->route()));
            }
            fail('操作失败');
        }

        if(empty($order_id)){
            fail('请去礼包详情选择订单');
        }
        $order = (new \app\index\model\Order())->find($order_id);

        return $this->fetch('create', [
            "mate_title" => '反馈分类添加',
            'item' => $order
        ]);

    }


    /*
     * 删除
     */
    public function destroy($id)
    {

        if (FeedbackTypeModel::destroy($id)) {
            win('操作成功', Url::build('index'));
        }

        fail('操作失败');

    }

    /*
     * 编辑
     */
    public function update($id)
    {
        $get = Request::instance()->get();

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();
            $data2 = Request::instance()->route();

            // 验证
            $validate = Loader::validate('FeedbackType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());


            // 提交数据
            $dispose = (new FeedbackTypeModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose !== false) {
                win('操作成功', Url::build('index',$data2));
            }

            fail('操作失败');

        }

        $item = FeedbackTypeModel::get($id);

        $order_id = Request::instance()->param('order_id');
        $order = (new \app\index\model\Order())->find($order_id);

        return $this->fetch('create', [
            "mate_title" => '反馈分类编辑',
            'item2'       => $item,
            'item' => $order

        ]);
    }

    /*
     * 启用状态改变
     */
    public function auditing()
    {
        $id = Request::instance()->param('id');
        $status = FeedbackTypeModel::where('id', $id)->value('status') == '1' ? 2 : 1;
        if (FeedbackTypeModel::where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }

    /*
     * 排列顺序
     */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            FeedbackTypeModel::where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('FeedbackType/index'));
    }

    public function push($data, $name = 'Excel')
    {

        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '买家账号(车牌号)')
            ->setCellValue('C1', '订单号')
            ->setCellValue('D1', '送检人员')
            ->setCellValue('E1', '手机号码')
            ->setCellValue('F1', '车主姓名')
            ->setCellValue('G1', '车主号码')
            ->setCellValue('H1', '车牌号码')
            ->setCellValue('I1', '车辆识别码')
            ->setCellValue('J1', '发动机号')
            ->setCellValue('K1', '品牌型号')
            ->setCellValue('L1', '注册日期')
            ->setCellValue('M1', '创建日期')
            ->setCellValue('N1', '礼包名称')
            ->setCellValue('O1', '是否确认')

        ;

        $sheet1 = [];


        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;

        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['username']."({$v['car_number']})")
                ->setCellValue('C' . $num, $v['order_number_two'])
                ->setCellValue('D' . $num, "\t".$v['sjyr']."\t")
                ->setCellValue('E' . $num,  "\t".$v['tel']."\t")
                ->setCellValue('F' . $num, $v['car_name'])
                ->setCellValue('G' . $num, "\t".$v['car_tel']."\t")
                ->setCellValue('H' . $num, $v['car_number2'])
                ->setCellValue('I' . $num, $v['car_code'])
                ->setCellValue('J' . $num, $v['egine_number'])
                ->setCellValue('K' . $num, $v['brand_models'])
                ->setCellValue('L' . $num, $v['register_time'])
                ->setCellValue('M' . $num, $v['status'])
                ->setCellValue('N' . $num, $v['gift_title'])
                ->setCellValue('O' . $num, $v['create_time'])
            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('订单信息导出');
        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');
        exit;
    }
}
